<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" style="margin-top: 20px" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, onMounted, reactive } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './formView.data';
  import {
    getFormViewGetViewById,
    getFormViewUpdate,
    getFormViewCreate,
  } from '/@/api/formDesign/formDesign';

  export default defineComponent({
    name: 'FormViewModal',
    components: {
      BasicModal,
      BasicForm,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { createMessage } = useMessage();
      const isUpdate = ref(false);
      const dataRef = ref<Recordable>({});
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        setModalProps({ confirmLoading: false, width: '30%', minHeight: 60 });
        resetFields();
        try {
          dataRef.value = data?.record ?? {};
          isUpdate.value = data?.isUpdate;
          setFieldsValue({ ...dataRef.value });
        } catch (err) {
          console.log(err);
        }
      });

      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        labelWidth: 80,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const getTitle = computed(() => (isUpdate.value ? '编辑' : '新增'));

      async function handleSubmit() {
        try {
          setModalProps({ confirmLoading: true });

          const values = await validate();
          const formData = Object.assign({}, dataRef.value, values);
          console.log('formData', formData);
          if (!formData.id) {
            await getFormViewCreate(formData);
          } else {
            await getFormViewUpdate(formData);
          }
          createMessage.success('操作成功');
          closeModal();
          emit('success');
        } catch (err) {
          console.log(err);
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return {
        registerModal,
        getTitle,
        handleSubmit,
        registerForm,
      };
    },
  });
</script>
<style lang="less" scoped>
  :deep(.scrollbar__view) {
    :deep (div) {
      min-height: 80px;
    }
  }
</style>
